<?php

declare(strict_types=1);

namespace App\Dao;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\OilAmount as Model;
use App\Model\OilAmountChannel;

class OilAmountDao
{


    use DaoTrait;

    public function __construct()
    {
        $this->driver = __CLASS__;
    }

    /**
     * 根据分页与条件查询数据
     * @Author czm
     * @DateTime 2020-05-26
     * @param array $map
     * @param array $page
     * @param array $fields
     * @return void
     */
    public function pageByWhere($map = [], $page = [], $fields = [])
    {
        $model = Model::query();
        $model = $model->with(['oilAmountChannel.oilChannel']);
        if (!empty($fields)) {
            $model->select($fields);
        }
        $model = $model->when(!empty($map), function ($query) use ($map) {
            $query->where($map);
        });
        $count = $model->count();
        $data = $model->orderBy('sort', 'desc')->paginate(intval($page['pageSize']), ['*'], 'page', $page['page'])
            ->each(function ($value) {
                //查询关联
                if (!empty($value->oilAmountChannel)) {
                    $value->oilAmountChannel->each(function ($val) {
                        $val->forceFill([
                        'name' => $val->oilchannel->name ?? '', 
                        'start_time' => $val->oilchannel->start_time ?? '', 
                        'type' => $val->oilchannel->type ?? '', 
                        'channel_status' => $val->oilchannel->status ?? '',
                        'is_del' => $val->oilchannel->is_del ?? '',
                        ])
                        ->makeHidden(['oilChannel', 'oilchannel']);
                    });
                    //状态过滤
                    $channel_list = collect($value->oilAmountChannel->toArray())->sortByDesc('sort')->filter(function ($val) use ($value) {
                        return $val['start_time'] < time() && $val['type'] == $value->type_id && $val['channel_status'] == 1&& $val['is_del'] == 1;
                    })->toArray();
                    $channel_list =array_values($channel_list);
                }
                $value->forceFill([
                    'channel_list' => $channel_list ?? []
                ])->append(['type_mapping', 'status_mapping'])->makeHidden(['oilChannel', 'oilAmountChannel', 'oilchannel']);
            })->toArray();

        return compact('count', 'data');
    }

    //根据条件获取所有内容
    public function getByWhere($map = [], $fields = [], $scope = [], $orderBy = 'id', $sort = 'asc')
    {
        $model = Model::query();
        if (!empty($fields)) {
            $model->select($fields);
        }
        $data = $model->when(!empty($map), function ($query) use ($map) {
            $query->where($map);
        })->orderBy($orderBy, $sort)->get()->each(function ($value) {
            $value->append(['status_mapping']);
        });
        return $data;
    }

    //根据条件with关联数据获取所有内容
    public function getIndexByWhere($map = [], $fields = [], $scope = [], $orderBy = 'id', $sort = 'asc')
    {
        $model = Model::query();
        if (!empty($fields)) {
            $model->select($fields);
        }
        $data = $model->whereHas('oilAmountChannel.oilChannel',function($query){
            $query->where('oil_amount_channel.status',2)->where('oil_channel.status',1)->where('oil_channel.start_time','<',time())->where('oil_channel.is_del',1);
        })->when(!empty($map), function ($query) use ($map) {
            $query->where($map);
        })->orderBy($orderBy, $sort)->get()->each(function ($value) {
            $value->append(['status_mapping']);
        });
        return $data;
    }

    /**
     * 判断充值金额是否存在,存在返回正常状态的 -id
     * @Author czm
     * @DateTime 2020-04-20
     * @param [type] $ori_amount 初始金额
     * @param [type] $type_id  1中石油 2中石化 
     * @return mixed
     */
    public function isLegalAmount($ori_amount, $type_id)
    {
        $id = Model::where('type_id', $type_id)->where('ori_amount', $ori_amount)->where('status', 1)->value('id');
        if (!empty($id)) {
            return $id;
        } else {
            return false;
        }
    }


    /**
     * 判断充值折扣金额是否合法,存在返回正常状态的 -商品信息
     * @Author czm
     * @DateTime 2020-04-20
     * @param [type] $ori_amount 初始金额
     * @param [type] $amount 售价金额
     * @param [type] $type_id  1中石油 2中石化
     * @return mixed
     */
    public function isLegalDisCountAmount($ori_amount, $amount, $type_id)
    {
        $info = Model::where('type_id', $type_id)
            ->where('amount', $amount)
            ->where('ori_amount', $ori_amount)->where('status', 1)->first();
        if (!empty($info)) {
            return $info->toArray();
        } else {
            return false;
        }
    }

    //根据id修改关联状态
    public function updateChannelStatusById($id)
    {
        $info = OilAmountChannel::find($id);
        if (empty($info)) {
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '检测更新数据为空');
        }
        $info->status = $info->status == 1 ? 2 : 1;
        return $info->save();
    }


    /**
     * 查询
     * @param $where
     * @param string[] $columns
     * @return array
     */
    public function searchByWhere($where, $columns = ['*'])
    {
        return Model::query()->where($where)->orderBy('sort', 'desc')->get($columns)->toArray();
    }
}
